import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, ICoolCache } from 'midwayjs-cool-core';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { MallCategoryEntity } from '../entity/category';

@Provide()
export class MallCategoryService extends BaseService {
  @InjectEntityModel(MallCategoryEntity)
  mallCategoryEntity: Repository<MallCategoryEntity>;

  @Inject('cool:cache')
  coolCache: ICoolCache;

  /**
   * 用 JSON 数据初始化 category 表，规则
   *  - xx：一级分类
   *  - xxxx：二级分类
   *  - xxxxxx：三级分类
   * 备注：更建议自定义 id 而不是按顺序初始化 id
   * Todo：可以更新为递归实现
   * @param params
   */
  async initialize(params: any) {
    let cateId1 = 1;
    for (const cate1 of params.children) {
      // 存储一级分类
      await this.mallCategoryEntity.save({
        categoryId: cateId1,
        level: 1,
        parent: 0,
        name: cate1.name,
      });

      let cateId2 = 1;
      for (const cate2 of cate1.children) {
        // 存储二级分类
        await this.mallCategoryEntity.save({
          categoryId: cateId1 * 100 + cateId2,
          level: 2,
          parent: cateId1,
          name: cate2.name,
        });

        let cateId3 = 1;
        for (const cate3 of cate2.children) {
          // 存储三级分类
          await this.mallCategoryEntity.save({
            categoryId: cateId1 * 10000 + cateId2 * 100 + cateId3,
            level: 3,
            parent: cateId1 * 100 + cateId2,
            name: cate3.name,
          });
          cateId3++;
        }
        cateId2++;
      }
      cateId1++;
    }
  }
}
